package com.ruoyi.materials.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.materials.domain.LwMaterialInfo;
import com.ruoyi.materials.domain.LwOrder;
import com.ruoyi.materials.mapper.LwMaterialInfoMapper;
import com.ruoyi.materials.mapper.LwOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.materials.mapper.LwMaterialMapper;
import com.ruoyi.materials.domain.LwMaterial;
import com.ruoyi.materials.service.ILwMaterialService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.validation.Validator;

/**
 * 原材料Service业务层处理
 * 
 * @author sl
 * @date 2023-08-04
 */
@Slf4j
@Service
public class LwMaterialServiceImpl implements ILwMaterialService 
{
    @Autowired
    private LwMaterialMapper lwMaterialMapper;

    @Autowired
    private LwMaterialInfoMapper lwMaterialInfoMapper;

    @Autowired
    private LwOrderMapper LwOrderMapper;

    /**
     * 查询原材料
     * 
     * @param materialId 原材料主键
     * @return 原材料
     */
    @Override
    public LwMaterial selectLwMaterialByMaterialId(Long materialId)
    {
        return lwMaterialMapper.selectLwMaterialByMaterialId(materialId);
    }

    /**
     * 查询原材料列表
     * 
     * @param lwMaterial 原材料
     * @return 原材料
     */
    @Override
    public List<LwMaterial> selectLwMaterialList(LwMaterial lwMaterial)
    {
        return lwMaterialMapper.selectLwMaterialList(lwMaterial);
    }

    /**
     * 查询后焊器件列表
     * @param lwMaterial
     */
    @Override
    public List<LwMaterial> selectBackWeldMaterialList(LwMaterial lwMaterial)
    {
        return lwMaterialMapper.selectBackWeldMaterialList(lwMaterial);
    }

    /**
     * 新增原材料
     * 
     * @param lwMaterial 原材料
     * @return 结果
     */
    @Override
    public int insertLwMaterial(LwMaterial lwMaterial)
    {
        lwMaterial.setQuantity(0L);
        return lwMaterialMapper.insertLwMaterial(lwMaterial);
    }

    /**
     * 修改原材料
     * 
     * @param lwMaterial 原材料
     * @return 结果
     */
    @Override
    public int updateLwMaterial(LwMaterial lwMaterial)
    {
        return lwMaterialMapper.updateLwMaterial(lwMaterial);
    }

    /**
     * 新增后焊材料
     */
    @Override
    public int addBackweldMaterial(LwMaterial lwMaterial) {
        LwMaterial material = lwMaterialMapper.selectLwMaterialByMaterialId(lwMaterial.getMaterialId());
        material.setIfBackweld(1L);
        if (lwMaterial.getRemark() != null){
            material.setRemark(lwMaterial.getRemark());
        }
        return lwMaterialMapper.updateLwMaterial(material);
    }
    /**
     * 删除后焊材料
     */
    @Override
    public int delBackweldMaterial(Long materialIds) {
        LwMaterial material = lwMaterialMapper.selectLwMaterialByMaterialId(materialIds);
        material.setIfBackweld(0L);
        return lwMaterialMapper.updateLwMaterial(material);
    }

    /**
     * 批量删除原材料
     * 
     * @param materialIds 需要删除的原材料主键
     * @return 结果
     */
    @Override
    public int deleteLwMaterialByMaterialIds(Long[] materialIds)
    {
        return lwMaterialMapper.deleteLwMaterialByMaterialIds(materialIds);
    }

    /**
     * 删除原材料信息
     * 
     * @param materialId 原材料主键
     * @return 结果
     */
    @Override
    public int deleteLwMaterialByMaterialId(Long materialId)
    {
        return lwMaterialMapper.deleteLwMaterialByMaterialId(materialId);
    }

    @Override
    public int updateMaterialQuantity(LwMaterial lwMaterial) {

        if (lwMaterial.getVariable() < 0 ){
            return -1;
        }
        if (lwMaterial.getRemove() > lwMaterial.getQuantity()){
            return -2;
        }
        // 新建原材料记录对象
        LwMaterialInfo materialInfo = new LwMaterialInfo();
        materialInfo.setMaterialId(lwMaterial.getMaterialId());
        materialInfo.setTime(new Date());
        materialInfo.setEmployeeId(SecurityUtils.getUserId());
        materialInfo.setRemark(lwMaterial.getInfoRemark());
        // 入库
        if (lwMaterial.getVariable() > 0) {
            lwMaterial.setQuantity(lwMaterial.getQuantity() + lwMaterial.getVariable());
            this.deductActualQuantity(lwMaterial.getMaterialNumber(),lwMaterial.getVariable());
            materialInfo.setFlow(1L);
            materialInfo.setCompleted(lwMaterial.getVariable());
        }
        //出库
        if (lwMaterial.getRemove() > 0){
            lwMaterial.setQuantity(lwMaterial.getQuantity() - lwMaterial.getRemove());
            materialInfo.setFlow(0L);
            materialInfo.setCompleted(lwMaterial.getRemove());
        }

        lwMaterialInfoMapper.insertLwMaterialInfo(materialInfo);

        return lwMaterialMapper.updateLwMaterial(lwMaterial);
    }

    @Autowired
    protected Validator validator;

    @Transactional
    @Log(title = "原材料入库excel导入", businessType = BusinessType.IMPORT)
    @Override
    public String importUser(List<LwMaterial> lwMaterialList, boolean isUpdateSupport, String operName) {
        if (StringUtils.isEmpty(lwMaterialList) || lwMaterialList.isEmpty()) {
            throw new ServiceException("导入原材料入库数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (LwMaterial material : lwMaterialList) {
            try {
                // 验证是否存在这个项目编号
                LwMaterial existingMaterial = lwMaterialMapper.selectLwMaterialByMaterialNumber(material.getMaterialNumber());
                if (Objects.isNull(existingMaterial)) {
                    BeanValidators.validateWithException(validator, material);
                    material.setCreateBy(operName);
                    this.insertMaterial(material);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、物料号 ").append(material.getMaterialNumber()).append(" 导入成功");
                } else {
                    BeanValidators.validateWithException(validator, material);
                    material.setUpdateBy(operName);
                    this.updateMaterial(material);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、物料号 ").append(material.getMaterialNumber()).append(" 更新成功");
                }
                // 新建原材料记录对象
                LwMaterialInfo materialInfo = new LwMaterialInfo();
                LwMaterial lwMaterial = lwMaterialMapper.selectLwMaterialByMaterialNumber(material.getMaterialNumber());
                materialInfo.setMaterialId(lwMaterial.getMaterialId());
                materialInfo.setTime(new Date());
                materialInfo.setEmployeeId(SecurityUtils.getUserId());
                materialInfo.setFlow(1L);
                materialInfo.setCompleted(material.getQuantity());
                lwMaterialInfoMapper.insertLwMaterialInfo(materialInfo);

            } catch (Exception e) {
                // 出现异常时，事务管理器会自动回滚之前的操作
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                failureNum++;
                String msg = "<br/>" + failureNum + "、物料号 " + material.getMaterialNumber() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
//                log.error(() -> msg, e);
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    private void updateMaterial(LwMaterial material) {
        LwMaterial lwMaterial = lwMaterialMapper.selectLwMaterialByMaterialNumber(material.getMaterialNumber());
        lwMaterial.setQuantity(material.getQuantity() + lwMaterial.getQuantity());
        this.deductActualQuantity(material.getMaterialNumber(),material.getQuantity());
        lwMaterialMapper.updateLwMaterial(lwMaterial);
    }

    private void insertMaterial(LwMaterial material) {
        this.deductActualQuantity(material.getMaterialNumber(),material.getQuantity());
        lwMaterialMapper.insertLwMaterial(material);
    }

    private void deductActualQuantity(String materialNumber, Long quantity) {
        LwOrder order = LwOrderMapper.selectLwOrderByMaterialNumber(materialNumber);
        long l = order.getActualArrival() - quantity;
        if (l < 0) {
            throw new IllegalArgumentException("实到数量不足，无法入库");
        }
        order.setActualArrival(l);
        LwOrderMapper.updateLwOrder(order);
    }

}
